extends Control

const ITEM_SCENE = preload("res://Scenes/PowerUpItem.tscn")
var total_hits = 0
var left_items = []
var right_items = []

var Y = 120
# 定时器变量
var timer: Timer

var currentUpCount = 0;

var viewport_size
func reset():
	total_hits = 0  # 重置为初始值
	# 销毁所有 left_items
	for item in left_items:
		if is_instance_valid(item):  # 确保节点未被提前销毁
			item.queue_free()        # 安全移除节点
	left_items.clear()               # 清空数组

	# 同样处理 right_items
	for item in right_items:
		if is_instance_valid(item):
			item.queue_free()
	right_items.clear()
	init_queues()
	
func _ready():
	
	viewport_size = get_viewport_rect().size
	
	init_queues()
	
	# 创建定时器
	timer = Timer.new()
	add_child(timer)

	# 设置定时器参数
	timer.wait_time = 2.0  # 每 2 秒执行一次
	timer.one_shot = false  # 设置为循环执行
	timer.timeout.connect(register_hit)  # 连接 timeout 信号到 register_hit 函数

	# 启动定时器
	timer.start()

func init_queues():
	# 初始化左右各4个道具
	for i in 4:
		var base_hits = 2 * pow(2, i)
		if i >= 8 :
			base_hits = 400 + 200*(i-8)
			
		add_item(left_items, Vector2(50, 200 +(3- i)*Y), base_hits)
		add_item(right_items, Vector2(viewport_size.x-50, 200 + (3- i)*Y), base_hits)

func add_item(queue, pos, base_hits):
	var item = ITEM_SCENE.instantiate()
	item.position = pos
	item.required_hits = base_hits
	await get_tree().process_frame # 等待一帧
	get_tree().current_scene.add_child(item)
	queue.push_back(item)
	
func register_hit():
	#total_hits += 1
	update_queues(left_items)
	update_queues(right_items)

func update_queues(queue):
	var isNot = false
	for item in queue:
		if not item:
			isNot =true
	if isNot:
		if(left_items == queue and left_items.size() > 0):
			left_items.remove_at(0)
			process_left_items(left_items)
		elif(right_items == queue  and right_items.size() > 0):
			right_items.remove_at(0)
			process_right_items(right_items)
		#add_new_item(queue)

# 假设 left_items 是一个包含节点的数组
func process_left_items(queue):
	# 1. 删除为 null 的元素
	queue = queue.filter(func(item): return item != null)
	# 2. 将所有节点的 y 坐标增加 100
	var x = 0
	var required_hits = 0
	for item in queue:
		if item is Node2D:  # 确保是 Node2D 节点
			item.position.y += Y
			x = item.position.x
			required_hits = item.required_hits
	
	if(required_hits <400):
		add_item(left_items, Vector2(50, 200), required_hits * 2)
	if(required_hits >=400):
		add_item(left_items, Vector2(50, 200), required_hits+200)
	

func process_right_items(queue):
	# 1. 删除为 null 的元素
	queue = queue.filter(func(item): return item != null)
	# 2. 将所有节点的 y 坐标增加 100
	var x = 0
	var required_hits = 0
	for item in queue:
		if item is Node2D:  # 确保是 Node2D 节点
			item.position.y += Y
			x = item.position.x
			required_hits = item.required_hits
	if(required_hits <400):
		add_item(right_items, Vector2(viewport_size.x-50, 200), required_hits * 2)		
	if(required_hits >=400):
		add_item(right_items, Vector2(viewport_size.x-50, 200), required_hits+200)
